package com.atguigu.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Date:2020/9/14
 * Author:ybc
 * Description:
 */
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String rememberMe = request.getParameter("rememberMe");
        //判断用户名和密码是否登录成功
        if("admin".equals(username) && "123456".equals(password)){
            //成功，则判断rememberMe，是否需要记住用户名和密码
            if(rememberMe != null){
                Cookie cookie1 = new Cookie("username", username);
                Cookie cookie2 = new Cookie("password", password);
                cookie1.setMaxAge(30*24*60*60);
                cookie2.setMaxAge(30*24*60*60);
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            }
            //重定向到成功页面
            response.sendRedirect(request.getContextPath() + "/testCookie/success.jsp");
        }else{
            //失败
            request.getRequestDispatcher("/testCookie/login.jsp").forward(request, response);
        }

    }
}
